"""Download Manager"""

# pylint: disable=line-too-long

from os import makedirs
from os.path import dirname, exists

from baidubce.protocol import HTTPS
from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials
from baidubce.services.bos.bos_client import BosClient
from loguru import logger

from ios_cov_manager.config.path import PROFRAW_DIR
from ios_cov_manager.config.bce import (
    ACCESS_KEY_ID,
    SECRET_ACCESS_KEY,
    BOS_HOST,
    BUCKET_NAME,
    PROFRAW_KEY_PATH,
)
from ios_cov_manager.model.branch_coverage import BranchCoverage
from ios_cov_manager.lib.disk_cache_util import DiskCacheUtil


class CoveragePlatformManager:
    """Coverage Platform Manager"""

    def __init__(self, platform_base_url: str, branch_coverage: BranchCoverage):
        self.platform_base_url = platform_base_url
        self.branch_coverage = branch_coverage

        config = BceClientConfiguration(
            credentials=BceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY),
            endpoint=BOS_HOST,
            protocol=HTTPS,
        )
        self.bos_client = BosClient(config)
        self.bucket_name = BUCKET_NAME

    def upload_coverage_report(self, coverage_report_path: str):
        """Upload a coverage report to the coverage platform

        :param coverage_report_path: Path of the coverage report file
        """
        if not coverage_report_path:
            raise ValueError("No coverage report path provided")

        # TODO 1 上传覆盖率报告到平台

    def download_profraws_and_artifacts(self):
        """Download the profraw files and the build artifacts"""

        self.download_profraw_files()
        # TODO 2 下载构建产物 Debug-iphoneos.zip 文件并解压缩到 Debug-iphoneos 目录
        # TODO 3 下载构建产物 macho 文件 jdcomiphone.o 到 macho_files 目录

    def download_profraw_files(self) -> None:
        """Download profraw files with the same version and branch name"""

        prefix = f"{PROFRAW_KEY_PATH}/{self.branch_coverage.version}/{self.branch_coverage.replaced_branch_name}/"
        logger.info(f"Downloading version level profraw, prefix: {prefix}")

        all_objects = self.bos_client.list_all_objects(
            bucket_name=BUCKET_NAME,
            prefix=prefix,
        )

        for obj in all_objects:
            obj_key: str = obj.key
            if not obj_key.endswith(".profraw"):
                continue
            if DiskCacheUtil.has(obj_key):
                etag_in_cache = DiskCacheUtil.get(obj_key)
                if obj.etag == etag_in_cache:
                    logger.info(
                        f"Profraw {obj_key} with etag {etag_in_cache} is already downloaded, no need to update"
                    )
                    continue
            else:
                DiskCacheUtil.set(obj_key, obj.etag)
            file_name = obj_key.split("/")[-1]
            logger.info(f"Downloading profraw: {file_name}")
            save_path = obj_key.replace(PROFRAW_KEY_PATH, PROFRAW_DIR)
            dir_path = dirname(save_path)
            if not exists(dir_path):
                makedirs(dir_path)
                logger.success(f"Created directory: {dir_path}")
            # Download profraw files from the bos
            self.bos_client.get_object_to_file(
                bucket_name=BUCKET_NAME,
                key=obj_key,
                file_name=save_path,
            )
